{% extends "app/base_site.html" %}

{% block title %} {% if  "add" == handle %}添加{% else %}编辑{% endif %}布控 {% endblock title %}

{% block stylesheets %}
  {{ block.super }}
    <style>
    .div_canvas_box{
        background: #e5e5e5;
        display: flex;
        position: relative;
    }
    .div_canvas_box>div{
        width: 100%;
        height: 100%;
        /*object-fit: fill;*/
        /*border-radius: 5px;*/
        /*border: 1px solid #f0f0f0;*/
    }
    .div_canvas_box>div:focus {
        outline: -webkit-focus-ring-color auto 0px;
    }
    .div_canvas_box>canvas{
        margin: 0 0;
        border: 1px solid darkred;
        position: absolute;
        top: 0;
        left: 0px;
        width: 100%;
        height: 100%;
        z-index: 6;
    }
    .div_left_bottom_menu{
        margin-top: 20px;
        padding: 5px;
        border: 1px solid #e5e5e5;
        color: #ffffff;
        background-color: #ffffff;
    }
    .div_left_bottom_draw{
        margin-top: 20px;
        padding: 5px;
        border: 1px solid #e5e5e5;
        color: #ffffff;
        background-color: #ffffff;

        display: flex;
        justify-content: center;
        align-items: center;
    }
    .div_left_bottom_draw>.item{
        flex:1;
        display: flex;
         justify-content: center;
        align-items: center;
        color: #000;
    }
    .div_left_bottom_draw>.item>.img{
        width: 120px;
        cursor: pointer;
    }
</style>

{% endblock stylesheets %}
{% block content %}

<script>
    let streamCodeDict = {};//视频流字典
    let streamCode;

    let flowDict = {};//算法字典
    let flowCode;

    let audioCodeDict = {}; //音频字典
    let audioCode;

    let m_alarmInterfaceCodeDict = {}; //报警接口字典
    let m_alarmInterfaceCode;


</script>
  <div class="right_col" role="main">
    <div class="">
      <div class="row">
        <div class="col-md-12 col-sm-12 col-xs-12">
          <div class="x_panel">
            <div class="x_title">
              <h2>{% if  "add" == handle %}添加{% else %}编辑{% endif %}布控
              </h2>
              <div class="clearfix"></div>
            </div>
            <div class="x_content">
              <div class="col-md-8 col-sm-8 col-xs-12">
                <div class="div_canvas_box">
                    <div id="video_player" style="background-color: black;aspect-ratio: 16 / 9;">
                    </div>
                   <canvas id="canvas" >
                        Your browser is too old which doesn't support h5 canvas
                   </canvas>
                </div>

                <div class="div_left_bottom_menu">
                  <button type="button" onclick="f_clickPlayStart()" class="btn btn-dark btn-sm"><i class="fa fa-play"></i> 播放 </button>
                  <button type="button" onclick="f_clickPlayStop()" class="btn btn-default btn-sm"><i class="fa fa-stop"></i> 停止 </button>
                  <button type="button" onclick="f_clearVideoCanvas()" class="btn btn-default btn-sm"><i class="fa fa-paint-brush"></i> 清空区域</button>
                  <div class="btn-group" style="margin-bottom: 5px;">
                      <button type="button" id="btn_draw_type1" class="btn btn-default btn-sm">矩形</button>
                      <button type="button" id="btn_draw_type2" class="btn btn-default btn-sm">多边形</button>
                      <button type="button" id="btn_draw_type4" class="btn btn-default btn-sm">方向线</button>
                  </div>
                </div>

                    <div class="div_left_bottom_draw" >
                        <div class="item">绘制图像参考</div>
                        <div class="item">
                            <img class="img" src="/static/images/demo.jpg"/>
                        </div>
                    </div>

              </div>

              <div class="col-md-4 col-sm-4 col-xs-12" >
                  <div class="form-horizontal form-label-left">
                  {% if  "edit" == handle %}
                        <div class="form-group">
                          <label class="control-label col-md-3 col-sm-3 col-xs-12">布控ID</label>
                          <div class="col-md-9 col-sm-9 col-xs-12">
                              <span style="height: 34px;line-height: 34px;padding: 6px 0;">{{ control.id }}</span>
                          </div>
                        </div>
                {% endif %}
                        <div class="form-group">
                          <label class="control-label col-md-3 col-sm-3 col-xs-12">布控编号</label>
                          <div class="col-md-9 col-sm-9 col-xs-12">
                              <span style="height: 34px;line-height: 34px;padding: 6px 0;">{{ control.code }}</span>
                          </div>
                        </div>

                    <div class="form-group">
                          <label class="control-label col-md-3 col-sm-3 col-xs-12">选择视频流<span class="required" style="color: red;">*</span></label>
                        <div class="col-md-9 col-sm-9 col-xs-12">
                            {% if  "add" == handle %}
                              <select  id="select_stream" class="select2_single form-control" required="required" >
                                  {% if streams|length == 0 %}
                                      <option value="-1">暂无视频流</option>
                                  {% else %}
                                      <option value="0">请选择视频流</option>

                                    {% for stream in streams %}
                                        <script>
                                            streamCode = '{{ stream.code }}';
                                            streamCodeDict[streamCode] = {
                                                'code':streamCode,
                                                "app":'{{ stream.app }}',
                                                "name":'{{ stream.name }}',
                                                "video":'{{ stream.video }}',
                                                "video_codec_name":'{{ stream.video_codec_name }}',
                                                "video_width":parseInt('{{ stream.video_width }}'),
                                                "video_height":parseInt('{{ stream.video_height }}'),
                                                "audio":'{{ stream.audio }}',
                                                "videoUrl":'{{ stream.videoUrl }}',
                                                "wsHost":'{{ stream.wsHost }}',
                                                "wsMp4Url":'{{ stream.wsMp4Url }}',
                                                "source_nickname":'{{ stream.source_nickname }}'
                                            }
                                        </script>
                                        <option value="{{ stream.code }}">{{ stream.source_nickname }}</option>
                                    {% endfor %}
                                  {% endif %}
                              </select>
                         {% else %}
                                <!-- 编辑 -->
                              <select id="select_stream"  disabled="disabled"  class="select2_single form-control" >
                                <option selected value="{{ control_stream.code }}">{{ control_stream.nickname}}</option>
                              </select>
                         {% endif %}
                       </div>
                   </div>


                    <div class="form-group">
                      <label class="control-label col-md-3 col-sm-3 col-xs-12">视频信息</label>
                      <div class="col-md-9 col-sm-9 col-xs-12">
                             <input id="input_video"  type="text" disabled="disabled" value="{{ control.stream_video }}" class="form-control">
                      </div>
                    </div>

                    <div class="form-group">
                      <label class="control-label col-md-3 col-sm-3 col-xs-12">音频信息</label>
                      <div class="col-md-9 col-sm-9 col-xs-12">
                           <input id="input_audio"  type="text" disabled="disabled" value="{{ control.stream_audio }}" class="form-control">
                      </div>
                    </div>



                    <div class="form-group">
                      <label class="control-label col-md-3 col-sm-3 col-xs-12">播放地址</label>
                      <div class="col-md-9 col-sm-9 col-xs-12">
                           <input id="input_video_url"  type="url" disabled="disabled" class="form-control">
                      </div>
                    </div>

                          <div class="ln_solid"></div>


                    <div class="form-group">
                          <label class="control-label col-md-3 col-sm-3 col-xs-12">业务算法<span class="required" style="color: red;">*</span>
                          </label>

                          <div class="col-md-9 col-sm-9 col-xs-12">

                            <select id="select_flow"  class="select2_single form-control" required="required" >
                                <option value="0">请选择业务算法</option>
                                {% for flow in flows %}
                                   <script>
                                        flowCode = '{{ flow.code }}';
                                        flowDict[flowCode] = {
                                            "code":flowCode,
                                            "name":'{{ flow.name }}'
                                        }
                                    </script>

                                    <option {% if flow.code == control.flow_code %} selected {% endif %} value="{{ flow.code }}">{{ flow.name }}</option>
                                {% endfor %}
                            </select>

                          </div>
                    </div>



                        <div class="form-group">
                          <label class="control-label col-md-3 col-sm-3 col-xs-12">报警音频<span class="required" style="color: red;">*</span>
                          </label>

                          <div class="col-md-9 col-sm-9 col-xs-12">

                            <select id="select_audio"  class="select2_single form-control" required="required" >
                                <option value="0">请选择报警音频</option>
                                {% for audio in audios %}
                                   <script>
                                        audioCode = '{{ audio.code }}';

                                        audioCodeDict[audioCode] = {
                                            "code":audioCode,
                                            "name":'{{ audio.name }}'
                                        }

                                    </script>

                                    <option {% if audio.code == control.audio_code %} selected {% endif %} value="{{ audio.code }}">{{ audio.name }}</option>
                                {% endfor %}
                            </select>

                          </div>
                    </div>

                      <div class="form-group">
                          <label class="control-label col-md-3 col-sm-3 col-xs-12">报警接口<span class="required" style="color: red;">*</span>
                          </label>

                          <div class="col-md-9 col-sm-9 col-xs-12">

                            <select id="select_alarm_interface"  class="select2_single form-control" required="required" >
                                <option value="0">请选择报警接口</option>
                                {% for alarmInterface in alarmInterfaces %}
                                   <script>
                                        m_alarmInterfaceCode = '{{ alarmInterface.code }}';
                                        m_alarmInterfaceCodeDict[m_alarmInterfaceCode] = {
                                            "code":m_alarmInterfaceCode,
                                            "name":'{{ alarmInterface.name }}'
                                        }
                                    </script>

                                    <option {% if alarmInterface.code == control.alarm_interface_code %} selected {% endif %} value="{{ alarmInterface.code }}">{{ alarmInterface.name }}</option>
                                {% endfor %}
                            </select>

                          </div>
                    </div>

                  <div class="form-group">
                      <label class="control-label col-md-3 col-sm-3 col-xs-12">报警间隔<span class="required" style="color: red;">*</span> <i class="bxc_introduce fa fa-info-circle" title="单路布控强制最低报警间隔时长（单位秒）"></i></label>
                      <div class="col-md-9 col-sm-9 col-xs-12">
                           <input id="min_interval"  type="number" value="{{ control.min_interval }}" class="form-control" >
                      </div>
                    </div>

                  <div class="form-group">
                      <label class="control-label col-md-3 col-sm-3 col-xs-12">重叠比例<span class="required" style="color: red;">*</span> <i class="bxc_introduce fa fa-info-circle" title="检测目标位于绘制区域部分占目标整体的比例"></i></label>
                      <div class="col-md-9 col-sm-9 col-xs-12">
                           <input id="overlap_thresh"  type="number" value="{{ control.overlap_thresh }}" class="form-control" >
                      </div>
                    </div>

                  <div class="form-group">
                      <label class="control-label col-md-3 col-sm-3 col-xs-12">图片数量<span class="required" style="color: red;">*</span> <i class="bxc_introduce fa fa-info-circle" title="决策报警的图片数量"></i></label>
                      <div class="col-md-9 col-sm-9 col-xs-12">
                           <input name="alarm_image_count"  type="number" value="{{ control.alarm_image_count }}" class="form-control" >
                      </div>
                    </div>


                <div class="form-group">
                      <label class="control-label col-md-3 col-sm-3 col-xs-12">画框选项<span class="required" style="color: red;">*</span> <i class="bxc_introduce fa fa-info-circle" title="合成报警图片或视频时画框类型"></i></label>
                      <div class="col-md-9 col-sm-9 col-xs-12">

                          <div class="radio">
                              <label>
                                <input type="radio" {% if control.alarm_draw_type == 0 %} checked="checked" {% endif %} value="0" name="alarm_draw_type"> 画框
                              </label>
                            </div>

                            <div class="radio">
                              <label>
                                <input type="radio" {% if control.alarm_draw_type == 1 %} checked="checked" {% endif %} value="1" name="alarm_draw_type"> 不画框
                              </label>
                            </div>

                            <div class="radio">
                              <label>
                                <input type="radio" {% if control.alarm_draw_type == 2 %} checked="checked" {% endif %} value="2" name="alarm_draw_type"> 画框+不画框
                              </label>
                            </div>

                      </div>
                    </div>

                  <div class="form-group">
                      <label class="control-label col-md-3 col-sm-3 col-xs-12" for="textarea">OSD
                      </label>
                      <div class="col-md-9 col-sm-9 col-xs-12">
                        <textarea rows="4" name="osd_params" class="form-control col-md-7 col-xs-12">{{ control.osd_params }}</textarea>
                      </div>
                </div>

                  <div class="form-group">
                      <label class="control-label col-md-3 col-sm-3 col-xs-12" for="textarea">扩展参数
                      </label>
                      <div class="col-md-9 col-sm-9 col-xs-12">
                        <textarea rows="3" name="extend_params" class="form-control col-md-7 col-xs-12">{{ control.extend_params }}</textarea>

                      </div>
                </div>

               <div class="form-group">
                      <label class="control-label col-md-3 col-sm-3 col-xs-12" for="textarea">备注
                      </label>
                      <div class="col-md-9 col-sm-9 col-xs-12">
                        <textarea required="required" name="remark" class="form-control col-md-7 col-xs-12">{{ control.remark }}</textarea>

                      </div>
                </div>

                      <div class="ln_solid"></div>

                        <div class="form-group">
                          <div class="col-md-9 col-sm-9 col-xs-12 col-md-offset-3">
                            <button type="button" onclick="window.history.go(-1)" class="btn btn-default">返回</button>
                            <button type="button" onclick="f_openHandle()" class="btn btn-dark">提交</button>
                          </div>
                        </div>

                    </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
{% endblock content %}

{% block javascripts %}
  {{ block.super }}
<script src="/static/lib/easyPlayer/js/easyplayer-pro.js?02"></script>
<script src="/static/vendors/canvas_select/canvas-select.min.js"></script>
<script>
    let mNodeCode= '{{ node_code }}';// 节点编号
    let controlCode= '{{ control.code }}';// 布控编号
    let mPolygon = '{{ control.polygon }}';// 布控多边形坐标点
    let mPolygonType = parseInt('{{ control.polygon_type }}');// string类型->int 0:未绘制 1:矩形 2:方向线 3:多边形
    if(isNaN(mPolygonType)){
        mPolygonType = 1;//默认是矩形类型
    }
    let handle = '{{ handle }}';// 操作类型 add 或 edit
    let eleDivCanvasBox=document.querySelector('.div_canvas_box')
    let eleVideoPlayer = document.querySelector('#video_player');
    let mVideoUrl = null;
    let eleSelectStream = $("#select_stream");// select  选择视频流
    let eleInputVideoUrl= $("#input_video_url");// input
    let eleInputVideo = $("#input_video");// input
    let eleInputAudio = $("#input_audio");// input
    let eleSelectFlow = $("#select_flow");// select 算法

    let eleSelectAudio = $("#select_audio");// select 音频
    let eleSelectAlarmInterface = $("#select_alarm_interface");// select 报警接口

    let eleInputMinInterval = $("#min_interval");
    let eleInputOverlapThresh = $("#overlap_thresh");

    // 报警图片数量
    let eleInputAlarmImageCount= $("input[type=number][name='alarm_image_count']");
    // 报警视频是否画框
    let eleRadioAlarmDrawType = $('input[type=radio][name=alarm_draw_type]');//radio
    let alarmDrawType = $('input[type=radio][name=alarm_draw_type]:checked').val();

    let eleTextarea_osd_params = $("textarea[name='osd_params']");
    let eleTextarea_extend_params = $("textarea[name='extend_params']");
    let eleTextarea_remark = $("textarea[name='remark']");

    let eleBtnDrawType1 = $("#btn_draw_type1");
    let eleBtnDrawType2 = $("#btn_draw_type2");
    let eleBtnDrawType4 = $("#btn_draw_type4");

    let eleCanvas=document.getElementById("canvas");
    canvas.width= eleVideoPlayer.clientWidth
    canvas.height = eleVideoPlayer.clientHeight
    let instance = new CanvasSelect("#canvas", canvas.toDataURL());

    console.log("eleVideoPlayer.clientWidth:",eleVideoPlayer.clientWidth)
    console.log("eleVideoPlayer.clientHeight:",eleVideoPlayer.clientHeight)

    let option = [];
    instance.labelMaxLen = 10;
    //   instance.setData(option);
    function f_changeCreateType(createType) {
        console.log("f_changeCreateType->",createType)
        instance.createType = createType; // 0 不创建(默认)，1创建矩形，2创建多边形，3点标注，4折线标注，5圆形标注，6网格标注
        if(createType === 1){
            mPolygonType = 1;//矩形
        }else if(createType === 2){
            mPolygonType = 3;//多边形
        }else if(createType === 4 || createType === 6){
            mPolygonType = 2;//方向线
        }else{
            mPolygonType = 0;//未绘制或不支持的绘制类型
        }

        //调整显示按钮
        if(mPolygonType===1){
            eleBtnDrawType1.removeClass("btn-default");
            eleBtnDrawType1.addClass("btn-dark");
            eleBtnDrawType2.removeClass("btn-dark");
            eleBtnDrawType2.addClass("btn-default");
            eleBtnDrawType4.removeClass("btn-dark");
            eleBtnDrawType4.addClass("btn-default");
        }else if(mPolygonType === 3){
            eleBtnDrawType1.removeClass("btn-dark");
            eleBtnDrawType1.addClass("btn-default");
            eleBtnDrawType2.removeClass("btn-default");
            eleBtnDrawType2.addClass("btn-dark");
            eleBtnDrawType4.removeClass("btn-dark");
            eleBtnDrawType4.addClass("btn-default");
        }else if(mPolygonType === 2){
            eleBtnDrawType1.removeClass("btn-dark");
            eleBtnDrawType1.addClass("btn-default");
            eleBtnDrawType2.removeClass("btn-dark");
            eleBtnDrawType2.addClass("btn-default");
            eleBtnDrawType4.removeClass("btn-default");
            eleBtnDrawType4.addClass("btn-dark");
        }
    }

    eleBtnDrawType1.click(function () {
        f_changeCreateType(1);
    })
    eleBtnDrawType2.click(function () {
        f_changeCreateType(2);
    })
    eleBtnDrawType4.click(function () {
        f_changeCreateType(4);
    })

    instance.on("load", (src) => {
    });
    // 添加
    instance.on("add", (info) => {
        console.log("add->info.type",info.type);
        if(info.type === 1){//绘制矩形，支持多个矩形
            option.push(info);
        }else if(info.type === 2){//绘制多边形，支持多个多边形
            option.push(info);
        }else if(info.type === 4 || info.type === 6){//绘制方向线，仅支持绘制一个方向线
            if(option.length > 0){
                if(option[0].type === 4){//第一个图形必须是类型4
                }else{
                    f_clearVideoCanvas();
                    f_changeCreateType(4);
                    alert("绘制类型不正确，请重试");
                    return;
                }
            }
            if (info.type === 4) {
                f_changeCreateType(6)
            }
            option.push(info);
            let info_type = info.type.toString();
            if (option.length === 2) {
                if(info.type === 6) {
                    let ind = option.length
                    let line = option[ind - 2] // 拿到直线
                    let res = f_calcuTwoLineIntersect(line.coor[0], line.coor[1], info.coor[0], info.coor[1]);
                    if (!res) {
                        alert("方向线交叉不合规c1-"+info_type);
                        option.pop()
                        instance.setData(option);

                    }
                }else{
                    f_clearVideoCanvas();
                    f_changeCreateType(4);
                    alert("方向线类型不合规c1-"+info_type);
                }
            } else if (option.length === 3) {
                if (info.type === 6) {
                    let ind = option.length
                    let line = option[ind - 2] // 拿到直线
                    let res = f_calcuTwoLineIntersect(line.coor[0], line.coor[1], info.coor[0], info.coor[1]);
                    if (!res) {
                        alert("方向线交叉不合规c2-"+info_type);
                        option.pop()
                        instance.setData(option);

                    }
                } else {
                    f_clearVideoCanvas();
                    f_changeCreateType(4);
                    alert("方向线类型不合规c2-"+info_type);
                }
            }
        }
    });
    // 删除
    instance.on("delete", (info) => {
        window.info = info;
    });
    // 选中
    instance.on("select", (shape) => {
        window.shape = shape;
    });
    instance.on("updated", (result) => {
      //   myAlert("请选择视频流", "error");
        const list = [...result];

        list.sort((a, b) => a.index - b.index);
    });


    //清空绘制区域数据
    function f_clearVideoCanvas() {
        console.log("f_clearVideoCanvas() 执行清空绘制区域数据");
        console.log("instance:",instance)

        option = [];
        instance.setData(option);

    }
    //窗口对齐
    function f_adjustVideoCanvas() {
        console.log("f_adjustVideoCanvas() 执行canvas与播放器对齐");
        //执行窗口对齐以后，此前的绘制区域数据，可能不在对应，因此需要刷新
        let w = eleVideoPlayer.offsetWidth;
        let h = eleVideoPlayer.offsetHeight;
        //console.log("eleVideoPlayer.offsetWidth:",eleVideoPlayer.offsetWidth)
        //console.log("eleVideoPlayer.offsetHeight:",eleVideoPlayer.offsetHeight)
        eleCanvas.style.width = String(w)+"px";
        eleCanvas.style.height = String(h)+"px";
        instance.setData(option);
        
    }
    //计算两条直线是否相交
    function f_calcuTwoLineIntersect(p1, q1, p2, q2) {
        // 计算直线1和直线2的a, b, c
        const a1 = q1[1] - p1[1];
        const b1 = p1[0] - q1[0];
        const c1 = a1 * p1[0] + b1 * p1[1];

        const a2 = q2[1] - p2[1];
        const b2 = p2[0] - q2[0];
        const c2 = a2 * p2[0] + b2 * p2[1];

        // 计算行列式
        const det = a1 * b2 - a2 * b1;

        // 没有交点
        if (det === 0) {
            return false;
        }

        // 计算交点坐标
        const x = (b2 * c1 - b1 * c2) / det;
        const y = (a1 * c2 - a2 * c1) / det;

        // 检查交点是否在两条线的段上
        return (
            (p1[0] <= x && x <= q1[0] && p2[0] <= x && x <= q2[0]) ||
            (p1[0] >= x && x >= q1[0] && p2[0] >= x && x >= q2[0]) ||
            (p1[1] <= y && y <= q1[1] && p2[1] <= y && y <= q2[1]) ||
            (p1[1] >= y && y >= q1[1] && p2[1] >= y && y >= q2[1])
        );
    }
    eleSelectStream.change(function () {
        streamCode = $(this).val();
        let stream = streamCodeDict[streamCode];
        if (stream) {
            let wsHost = stream["wsHost"];
            let video_codec_name = stream["video_codec_name"];
            let video_width = stream["video_width"];
            let video_height = stream["video_height"];
            let app = stream["app"];
            let name = stream["name"];
            let wsMp4Url = stream["wsMp4Url"];
            //let target_video_width = 1280;
            //let target_video_height = 720;
            //let target_video_width = video_width;
            //let target_video_height = video_height;

            let video_url = wsMp4Url;

            mVideoUrl = video_url;

            eleInputVideoUrl.val(video_url)
            eleInputVideo.val(stream["video"])
            eleInputAudio.val(stream["audio"])
            f_playStart(video_url);
        }else{
            eleInputVideoUrl.val("")
            eleInputVideo.val("")
            eleInputAudio.val("")
            f_playStop();
        }

        for (let i = 0; i < 10; i++) {
            setTimeout(function () {
                f_adjustVideoCanvas();
            }, i*200);
        }
    });

    eleRadioAlarmDrawType.change(function () {
       alarmDrawType = $(this).val();
       //console.log("alarmDrawType",alarmDrawType)

    });

    let ePlayer = null;
    function f_createEPlayer() {
        ePlayer = new EasyPlayerPro({
            container: eleVideoPlayer,
            videoBuffer: 0.1, // 缓存时长
            videoBufferDelay: Number(3), // 1000s 达到延迟重播(s)
            decoder: '/static/lib/easyPlayer/js/decoder-pro.js',
            isResize: true,
            text: "北小菜",
            loadingText: "加载中",
            debug: false,
            debugLevel: "debug",
            useMSE: true,
            useSIMD: false,
            useWCS: true,
            hasAudio: true,
            websocket1006ErrorReplay: true,
            networkDelayTimeoutReplay: true,
            useMThreading: true,
            showBandwidth: false, // 显示网速
            showPerformance: false, // 显示性能
            operateBtns: {
                fullscreen: false,
                screenshot: false,
                play: true,
                audio: false,
                ptz: false,
                quality: false,
                performance: false,
            },
            background: "/static/images/player_poster.jpg",
            timeout: 10,
            qualityConfig: ['普清', '高清', '超清'],
            forceNoOffscreen: true,
            isNotMute: false,
            heartTimeout: Number(7),//超出时间无数据重连(s)
            ptzClickType: 'mouseDownAndUp',
            ptzZoomShow: true,
            ptzMoreArrowShow: true,
            ptzApertureShow: true,
            ptzFocusShow: true,
            pauseAndNextPlayUseLastFrameShow: true,
            heartTimeoutReplayUseLastFrameShow: true,
            replayUseLastFrameShow: true, // 重播使用上一帧显示
            fullscreenWatermarkConfig: {
                text: "", //水印
            }
        });
    }

    function f_playStart(video_url){
        if(video_url === "" || typeof video_url === "undefined"){
            myAlert("请输入播放地址（支持ws-fmp4/http-fmp4）！","error");
            return false;
        }
        if(!video_url.endsWith(".mp4")){
            myAlert("视频流地址格式不正确！","error");
            return false;
        }
        if(video_url.startsWith("ws://") || video_url.startsWith("http://")){
            if (ePlayer) {
                ePlayer.destroy().then(() => {
                    f_createEPlayer();
                    ePlayer.play(video_url);
                });
            } else {
                f_createEPlayer();
                ePlayer.play(video_url);
            }
            f_resetPolygon()
        }else{
             myAlert("视频流地址格式不正确！","error");
             return false;
        }

    }
    function f_playStop(){
        if(ePlayer){
            //ePlayer.pause();
            ePlayer.destroy();
        }else{
            myAlert("播放器未启动！","error");
        }
        f_clearVideoCanvas()

    }
    function f_clickPlayStart() {
        if(mVideoUrl){
            f_playStart(mVideoUrl);
            for (let i = 0; i < 10; i++) {
                setTimeout(function () {
                    f_adjustVideoCanvas();
                }, i*200);
            }
        }

    }
    function f_clickPlayStop() {
        f_playStop();
        f_adjustVideoCanvas();
    }
    function f_openHandle() {
        streamCode = eleSelectStream.val().trim();//typeof string
        if(streamCode==="-1"){
            myAlert("暂无视频流","error");
            return;
        }else if(streamCode==="0"){
            myAlert("请选择视频流","error");
            return;
        }
        flowCode = eleSelectFlow.val().trim();//typeof string
        if(flowCode==="0"){
            myAlert("请选择算法","error");
            return;
        }

        audioCode = eleSelectAudio.val().trim();//typeof string
        if(audioCode==="0"){
            myAlert("请选择音频","error");
            return;
        }

        m_alarmInterfaceCode = eleSelectAlarmInterface.val().trim();//typeof string
        if(m_alarmInterfaceCode==="0"){
            myAlert("请选择报警接口","error");
            return;
        }

        let minInterval = parseInt(eleInputMinInterval.val());
        if(isNaN(minInterval)){
            myAlert("报警间隔时间不能为空","error");
            return;
        }
        if(minInterval<0){
            myAlert("报警间隔时间不能小于0秒","error");
            return;
        }

        let overlapThresh = parseFloat(eleInputOverlapThresh.val());
        if(isNaN(overlapThresh)){
            myAlert("重叠阈值不能为空","error");
            return;
        }

        if(overlapThresh<=0){
            myAlert("重叠阈值不能小于等于0","error");
            return;
        }
        if(overlapThresh>1){
            myAlert("重叠阈值不能大于1","error");
            return;
        }
        //报警合成图片数量start
        let alarmImageCount = parseInt(eleInputAlarmImageCount.val());
        if(isNaN(alarmImageCount)){
            myAlert("报警图片数量不能为空","error");
            return;
        }
        if(alarmImageCount<=0){
            myAlert("报警图片数量不能小于等于0","error");
            return;
        }
        if(alarmImageCount>50){
            myAlert("报警图片数量不能大于50","error");
            return;
        }
         //报警合成图片数量end

        let osd_params = eleTextarea_osd_params.val().trim();
        let extend_params = eleTextarea_extend_params.val().trim();
        let remark = eleTextarea_remark.val().trim();

        //canvas绘制区域
        let canvas_box_width = eleDivCanvasBox.clientWidth;
        let canvas_box_height = eleDivCanvasBox.clientHeight

        console.log("canvas_box_width->",canvas_box_width)
        console.log("canvas_box_height->",canvas_box_height)
        console.log("canvas_width->",eleCanvas.width)
        console.log("canvas_height->",eleCanvas.height)
        console.log("option.length->",option.length,option)
        console.log("instance.createType->",instance.createType)
        console.log("mPolygonType->",mPolygonType)

        let polygon_array=[]
        if(mPolygonType === 1){//矩形
            if(option.length > 0){
                for (let i = 0; i < option.length; i++) {
                    let info = option[i];
                    let topL = info.coor[0];
                    let botR = info.coor[1];
                    let topR = [botR[0], topL[1]];
                    let botL = [topL[0], botR[1]];
                    // 四个点
                    let item = []
                    item.push((topL[0]/canvas_box_width).toFixed(4));
                    item.push((topL[1]/canvas_box_height).toFixed(4));
                    item.push((topR[0]/canvas_box_width).toFixed(4));
                    item.push((topR[1]/canvas_box_height).toFixed(4));
                    item.push((botR[0]/canvas_box_width).toFixed(4));
                    item.push((botR[1]/canvas_box_height).toFixed(4));
                    item.push((botL[0]/canvas_box_width).toFixed(4));
                    item.push((botL[1]/canvas_box_height).toFixed(4));
                    polygon_array.push(item.join(","))
                }
            }else{
                //矩形未绘制->全屏
                let item = []
                item.push(0);
                item.push(0);
                item.push(0);
                item.push(1);
                item.push(1);
                item.push(1);
                item.push(1);
                item.push(0);
                polygon_array.push(item.join(","))
            }
        }else if(mPolygonType === 2){//方向线
            if(option.length === 2){
                let info1 = option[0];
                let info2 = option[1];
                let topL= info1.coor[0];
                let topR= info1.coor[1];
                let botL= info2.coor[0];
                let botR= info2.coor[1];
                  // 四个点
                let item = []
                item.push((topL[0] / canvas_box_width).toFixed(4));
                item.push((topL[1] / canvas_box_height).toFixed(4));
                item.push((topR[0] / canvas_box_width).toFixed(4));
                item.push((topR[1] / canvas_box_height).toFixed(4));
                item.push((botR[0] / canvas_box_width).toFixed(4));
                item.push((botR[1] / canvas_box_height).toFixed(4));
                item.push((botL[0] / canvas_box_width).toFixed(4));
                item.push((botL[1] / canvas_box_height).toFixed(4));

                polygon_array.push(item.join(","))
            }else{
                myAlert("方向线类型必须是两条直线","error");
                return;
            }
        }else if(mPolygonType === 3){//多边形
            if(option.length > 0){
                for (let i = 0; i < option.length; i++) {
                    let info = option[i];
                    // 至少3个点
                    let item = []
                    for (let j = 0; j < info.coor.length; j++) {
                        item.push((info.coor[j][0]/canvas_box_width).toFixed(4));
                        item.push((info.coor[j][1]/canvas_box_height).toFixed(4));
                    }
                    polygon_array.push(item.join(","))

                }
            }else{
                //多边形未绘制->全屏
                let item = []
                item.push(0);
                item.push(0);
                item.push(0);
                item.push(1);
                item.push(1);
                item.push(1);
                item.push(1);
                item.push(0);
                polygon_array.push(item.join(","))
            }
        }else{
            myAlert("绘制类型错误:"+mPolygonType.toString(),"error");
            return;
        }
        console.log("polygon_array.length->",polygon_array.length)
        console.log("polygon_array->",polygon_array)
        
        let polygon = polygon_array.join("#");
        // 判断类型
        let data = {
            "node_code":mNodeCode,
            "controlCode":controlCode,
            "flowCode":flowCode,
            "audioCode":audioCode,
            "alarmInterfaceCode":m_alarmInterfaceCode,
            "polygon":polygon,
            "polygon_type": mPolygonType,
            "minInterval":minInterval,
            "overlapThresh":overlapThresh,
            "alarmDrawType":alarmDrawType,
            "alarmImageCount":alarmImageCount,
            "osd_params":osd_params,
            "extend_params":extend_params,
            "remark":remark
        }

        let handleUrl;
        if("add" === handle){
            handleUrl = "/control/openAdd";
            let stream = streamCodeDict[streamCode];
            if (stream){
                data["streamApp"] = stream["app"]
                data["streamName"] = stream["name"]
                data["streamVideo"] = stream["video"]
                data["streamAudio"] = stream["audio"]
            }else{
                return;
            }
        }
        else if("edit" === handle){
            handleUrl = "/control/openEdit";
        }
        else{
            return;
        }
        $.ajax({
           url: handleUrl,
           type: "post",
           async: true,
           data: data,
           dataType: "json",
           timeout: "3000",
           error: function () {
                myAlert("网络异常，请确定网络正常！","error",3000);
           },
           success: function (res) {
               if(1000 === res.code){
                    myAlert(res.msg,"success");
               }else{
                    myAlert(res.msg,"error",3000);
               }
           }
        });

    }

    window.onresize = function () {
        f_adjustVideoCanvas();
    }

    function f_resetPolygon(){
        if (mPolygon !== "") {//编辑布控
            f_adjustVideoCanvas();
            
            let canvas_box_width = eleDivCanvasBox.clientWidth;
            let canvas_box_height = eleDivCanvasBox.clientHeight
            let polygon_array = mPolygon.split('#')
            let polygon_item_length = polygon_array.length
            if (mPolygonType === 1)
            {
                option = []
                for (let i = 0; i < polygon_item_length; i++) {
                    let item = polygon_array[i].split(",");
                    let topLx = parseInt(item[0] * canvas_box_width)
                    let topLy = parseInt(item[1] * canvas_box_height)
                    let bomRx = parseInt(item[4] * canvas_box_width)
                    let bomRy = parseInt(item[5] * canvas_box_height)
                    let topL = [topLx, topLy];
                    let bomR = [bomRx, bomRy];
                    let obj = {
                        type: 1,
                        coor: [topL, bomR]
                    }
                    option.push(obj)
                }
                instance.setData(option)
            }else if (mPolygonType === 2)
            {
                if(polygon_item_length === 1){
                    option = []
                    for (let i = 0; i < polygon_item_length; i++) {
                        let item = polygon_array[i].split(",");
                        let objL = {
                            "coor": [],
                            "type": 4
                        }
                        let objLa = {
                            "coor": [],
                            "type": 6
                        }
                        for (let i = 0; i < item.length; i++) {
                            if (i % 2 === 0) {
                                if (i > 3) {
                                    let x = item[i] * canvas_box_width
                                    let y = item[i + 1] * canvas_box_height
                                    objLa.coor.unshift([x, y])
                                } else {
                                    let x = item[i] * canvas_box_width
                                    let y = item[i + 1] * canvas_box_height
                                    objL.coor.push([x, y])
                                }
                            }
                        }

                        option.push(objL)
                        option.push(objLa)

                    }
                    instance.setData(option)
                }
            }else if (mPolygonType === 3)
            {
                option = []
                for (let i = 0; i < polygon_item_length; i++) {
                    let item = polygon_array[i].split(",");
                    let line_count = item.length / 2;
                    let obj = {
                        type: 2,//多边形类型
                        coor: []
                    }
                    for (let j = 0; j < line_count; j++) {
                        let x = parseInt(item[j * 2] * canvas_box_width)
                        let y = parseInt(item[j * 2 + 1] * canvas_box_height)
                        obj.coor.push([x,y])
                    }
                    option.push(obj)
                }
                instance.setData(option)
            }
        }
    }
    $(function() {
        if(mPolygonType === 1){
            f_changeCreateType(1);
        }else if(mPolygonType === 2){
            f_changeCreateType(4);
        }else if(mPolygonType === 3){
            f_changeCreateType(2);
        }

        if(handle==="edit"){
            //编辑 start
            let is_online = parseInt("{{ control_stream.is_online }}");
            let app = "{{ control_stream.app }}";
            let name = "{{ control_stream.name }}";
            let video_codec_name = "{{ control_stream.video_codec_name }}";
            let video_width = parseInt("{{ control_stream.video_width }}");
            let video_height = parseInt("{{ control_stream.video_height }}");
            let wsHost = "{{ control_stream.wsHost }}";
            let wsMp4Url = "{{ control_stream.wsMp4Url }}";
            //let httpMp4Url = "{{ control_stream.httpMp4Url }}";
            //let rtspUrl = "{{ control_stream.rtspUrl }}";

            let video_url = wsMp4Url;
            mVideoUrl = video_url;
            eleInputVideoUrl.val(video_url);

            f_playStart(video_url);
            f_adjustVideoCanvas();
             //编辑 end
        }

        setTimeout( () =>{
            f_resetPolygon();
        }, 1200);

    });

</script>

{% endblock javascripts %}
